package com.yuanda.wordhot.util;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.event.ConfigurationEvent;
import org.apache.commons.configuration.event.ConfigurationListener;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 基于 Apache Common Configuration的配置帮助类
 * @author YuBai
 * @Description
 * @Date 2013-4-3
 * @version 1.0
 * @since 1.0
 */
public class ConfigUtil {
	private final static Log log = LogFactory.getLog(ConfigUtil.class);
	private static CompositeConfiguration config = null;// 组合配置 这个配置可以添加很多种配置
																											// 方便以后得管理
	static {
		try {
			log.info("Init System Config Properties……");
			config = new CompositeConfiguration();

			// 属性文件配置   如果有多个文件  可以再创建一个 属性文件配置  然后 添加到config里面
			PropertiesConfiguration properConfig = new PropertiesConfiguration("/application.properties");
			
			// 设置当文件发生变化的时候重新加载配置文件
			FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
			properConfig.setReloadingStrategy(strategy);
			config.addConfigurationListener(new ConfigChangeListener());
			config.addConfiguration(properConfig);
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}

	public static String getString(String key) {
		return config.getString(key);
	}

	public static boolean getBoolean(String key) {
		return config.getBoolean(key);
	}

	public static int getInt(String key) {
		return config.getInt(key);
	}

	public static void setProperty(String key, Object value) {
		config.setProperty(key, value);
	}
}

class ConfigChangeListener implements ConfigurationListener {

	@Override
	public void configurationChanged(ConfigurationEvent event) {
		System.out.println("Properties：" + event.getPropertyName() + " is changed to " + event.getPropertyValue());
	}

}